<template>
  <div class="board-container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>
        <span class="gray">当前位置</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>平台看板</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="top-toolbtn">
      <el-button class="editbtn" @click="isEdit=!isEdit">编辑</el-button>
      <el-button class="addbtn" @click="addDialogVisible=true">新增看板</el-button>
    </div>
    <div class="top-box">
      <el-col :span="6">
        <div class="contentbox new">
          <div class="num">
            <h2>新增用户数</h2>
            <h1>{{ kanbanData.newUserCount }}</h1>
            <span class="percent">+1.8%</span>
            <span>对比昨天</span>
          </div>
          <div>
            <img src="/image/wodedangxuan-2@2x.png" alt />
          </div>
        </div>
        <hr color="#5ad892" />
        <div class="showtime">
          <span>{{ "" | showDate }}</span>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="contentbox buy">
          <div class="num">
            <h2>课程访问量</h2>
            <h1>{{ kanbanData.courseVisit.todayCount }}</h1>
            <span class="percent">+1.8%</span>
            <span>对比昨天</span>
          </div>
          <div>
            <img src="/image/yanjing-4@2x.png" alt />
          </div>
        </div>
        <hr color="#5ba5f5" />
        <div class="showtime">
          <span>{{ "" | showDate }}</span>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="contentbox visit">
          <div class="num">
            <h2>课程购买量</h2>
            <h1>{{ kanbanData.courseBuy.todayCount }}</h1>
            <span class="percent">+1.8%</span>
            <span>对比昨天</span>
          </div>
          <div>
            <img src="/image/gouwuche@2x.png" alt />
          </div>
        </div>
        <hr color="#746fed" />
        <div class="showtime">
          <span>{{ "" | showDate }}</span>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="contentbox online">
          <div class="num">
            <h2>用户搜索量</h2>
            <h1>{{kanbanData.courseOnline.totalCount}}</h1>
            <span class="percent">+1.8%</span>
            <span>对比昨天</span>
          </div>
          <div>
            <img src="/image/sousuo-tianchong@2x.png" alt />
          </div>
        </div>
        <hr color="#9763ee" />
        <div class="showtime">
          <span>{{ "" | showDate }}</span>
        </div>
      </el-col>
    </div>

    <div class="chartsbox" v-loading.fullscreen.lock="loading">
      <el-col v-for="(item,index) in chartList" :key="index" :span="12">
        <div class="chart" @click="goToPage(item.url)">
          <div class="btn" v-if="isEdit">
            <img @click="editDialogShow(item)" src="/image/bianji.png" alt />
            <img @click="delItemFromChartList(index)" src="/image/shanchu.png" alt />
          </div>
          <chart-area
            :x-data="item.xlist"
            :chart-data="item.ylist"
            :tipName="item.tipname"
            :setheight="380"
            :isboard="true"
            :type="item.type"
            :chart-title="item.name"
            :date-str="item.dateStr"
          ></chart-area>
        </div>
      </el-col>
    </div>

    <!-- 编辑图表弹窗 -->
    <el-dialog
      :title="editData.name"
      :visible.sync="editDialogVisible"
      width="50%"
      :before-close="editDialogHandleClose"
      :destroy-on-close="true"
    >
      <div>
        <chart-area
          :x-data="editData.xlist"
          :chart-data="editData.ylist"
          :tipName="editData.tipname"
          :setheight="380"
          :type="editData.type"
          :timepicker="true"
          :toolbox="true"
          :picker-type="editData.fn=='getStatisticData'?'week':'daterange'"
          @changeType="editChartType"
          @reset-time="editChartData"
        ></chart-area>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editDialogHandleClose">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 新增图表弹窗 -->
    <el-dialog title="新增图表" :visible.sync="addDialogVisible" width="60%">
      <el-button-group>
        <el-button @click="checkNewChartType('line')">折线图</el-button>
        <el-button @click="checkNewChartType('bar')">柱形图</el-button>
        <el-button @click="checkNewChartType('hbar')">水平柱形图</el-button>
      </el-button-group>
      <div class="addbox">
        <el-row :gutter="40">
          <el-col :span="7">
            <div class="addborder">
              <div class="checkbox" v-for="(item,index) in fnList" :key="index">
                <p>{{ item.name }}</p>
                <div
                  :class="{'checkitem':true,'active':item.active}"
                  @click="checkChart(item,index)"
                >{{ chartList.findIndex(i => i.name == item.name) != -1?'已存在':'' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="17">
            <div class="addborder picbox">
              <img v-if="addChartType=='line'" src="/image/line.png" alt />
              <img v-if="addChartType=='bar'" src="/image/bar.png" alt />
              <img v-if="addChartType=='hbar'" src="/image/hbar.png" alt />
            </div>
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogHandleClose">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ChartArea from "@/components/ChartArea.vue";
import request from "@/utils/request";
import dayjs from "dayjs";
import {
  getBuyList,
  getOnlineData,
  getNewuserData,
  getStatisticData,
  getVisiList,
  getLiveList,
  getHotSubjectData
} from "@/utils/getChartsData";
export default {
  name: "Board",
  components: {
    "chart-area": ChartArea
  },
  data() {
    let queryDate = {
      startDate: dayjs()
        .subtract(10, "day")
        .format("YYYY-MM-DD"),
      endDate: dayjs().format("YYYY-MM-DD")
    };
    return {
      addDialogVisible: false,
      addChartType: "",
      addNewChartObj: null,
      editDialogVisible: false,
      editData: {},
      loading: false,
      isEdit: false,
      kanbanData: {
        courseVisit: {},
        courseBuy: {},
        courseOnline: {},
        courseAgent: {},
        newUserCount: 21694
      },
      chartList: [],
      startDate: dayjs()
        .subtract(10, "day")
        .format("YYYY-MM-DD"),
      endDate: dayjs().format("YYYY-MM-DD"),
      fnList: [
        {
          name: "课程购买量",
          fn: getBuyList,
          params: queryDate,
          active: false
        },
        {
          name: "课程访问量",
          fn: getVisiList,
          params: queryDate,
          active: false
        },
        {
          name: "在线学生人数",
          fn: getOnlineData,
          params: queryDate,
          active: false
        },
        {
          name: "新增用户人数",
          fn: getNewuserData,
          params: queryDate,
          active: false
        },
        {
          name: "活跃人数",
          fn: getLiveList,
          params: queryDate,
          active: false
        },
        {
          name: "机构销量",
          fn: getStatisticData,
          params: {
            datePickerSel: this.getPickerSel(new Date()),
            type: "year/month/week"
          },
          active: false
        },
        {
          name: "热门学科",
          fn: getHotSubjectData,
          params: {
            datePickerSel: this.getPickerSel(new Date()),
            type: "year/month/week"
          },
          active: false
        }
      ]
    };
  },
  async created() {
    this.initKanbanData();
    this.initCharts();
  },
  methods: {
    async initKanbanData() {
      const { data: res } = await request.get("/platformKanban/statistics");
      this.kanbanData = res.result;
    },
    async initCharts() {
      this.loading = true;
      let results = [];
      results.push(
        await getBuyList({
          startDate: this.startDate,
          endDate: this.endDate
        })
      );
      results.push(
        await getOnlineData({
          startDate: this.startDate,
          endDate: this.endDate
        })
      );
      results.push(
        await getStatisticData({
          datePickerSel: this.getPickerSel(new Date()),
          type: "year/month/week"
        })
      );
      results.push(
        await getNewuserData({
          startDate: this.startDate,
          endDate: this.endDate
        })
      );
      results.forEach(item => {
        if (item.fn != "getStatisticData") {
          item.dateStr = `${this.startDate} ~ ${this.endDate} `;
        } else {
          item.dateStr = this.getPickerSel(new Date()) + "周";
        }
      });
      this.chartList = results;
      this.loading = false;
    },
    // 处理周格式数据
    getPickerSel(date) {
      if (!date) {
        date = new Date();
      }
      let week = this.$dayjs(date).week();
      let year = this.$dayjs(date).format("YYYY");
      return `${year}/${this.$dayjs(date).format("YYYY-MM")}/${year}-${week}`;
    },
    // 删除图表
    async delItemFromChartList(index) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      if (result == "confirm") {
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.chartList.splice(index, 1);
      } else {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      }
      this.isEdit = false;
    },
    // 跳转到详情
    goToPage(url) {
      if (this.isEdit) {
        return false;
      }
      this.$router.push(url);
    },
    // 展示编辑弹窗
    editDialogShow(chart) {
      this.editDialogVisible = true;
      this.editData = chart;
    },
    // 编辑弹窗关闭
    editDialogHandleClose() {
      this.editDialogVisible = false;
      this.editData = {};
      this.isEdit = false;
    },
    // 改变图表类型
    editChartType(value) {
      this.editData.type = value;
    },
    // 改变图表数据
    async editChartData(newDate) {
      if (newDate instanceof Array) {
        let params = {
          startDate: dayjs(newDate[0]).format("YYYY-MM-DD"),
          endDate: dayjs(newDate[1]).format("YYYY-MM-DD")
        };
        let res = {};
        switch (this.editData.fn) {
          case "getBuyList":
            res = await getBuyList(params);
            break;
          case "getVisiList":
            res = await getVisiList(params);
            break;
          case "getOnlineData":
            res = await getOnlineData(params);
            break;
          case "getNewuserData":
            res = await getNewuserData(params);
            break;
          case "getLiveList":
            res = await getLiveList(params);
            break;
          default:
            break;
        }
        // 使用浅拷贝实现图表同步更新
        for (const key in res) {
          this.editData[key] = res[key];
        }
        this.editData.dateStr = `${params.startDate} ~ ${params.endDate} `;
      } else {
        let params = {
          datePickerSel: this.getPickerSel(newDate),
          type: "year/month/week"
        };
        let res = {};
        switch (this.editData.fn) {
          case "getStatisticData":
            res = await getStatisticData(params);
            break;
          case "getHotSubjectData":
            res = await getHotSubjectData(params);
            break;
          default:
            break;
        }
        // 使用浅拷贝实现图表同步更新
        for (const key in res) {
          this.editData[key] = res[key];
        }
        this.editData.dateStr = this.getPickerSel(newDate) + "周";
      }
    },
    async addDialogHandleClose() {
      if (!this.addNewChartObj) {
        this.$message.error("未选择要添加的图表");
      } else if (this.addChartType == "") {
        this.$message.error("未选择图表类型");
      } else {
        let res = await this.addNewChartObj.fn(this.addNewChartObj.params);
        res.type = this.addChartType;
        this.chartList.unshift(res);
      }
      this.addDialogVisible = false;
      this.addNewChartObj = null;
      this.addChartType = "";
      this.fnList.forEach(item => (item.active = false));
    },
    checkChart(checkObj, index) {
      if (this.chartList.findIndex(item => item.name == checkObj.name) != -1) {
        return this.$message.error("该图表已经存在");
      }
      this.fnList.forEach(item => (item.active = false));
      checkObj.active = true;
      this.addNewChartObj = this.fnList[index];
    },
    checkNewChartType(type) {
      this.addChartType = type;
    }
  },
  // 时间显示过滤器
  filters: {
    showDate: function(value) {
      return (
        dayjs()
          .subtract(1, "day")
          .format("YYYY-MM-DD") +
        " ~ " +
        dayjs().format("YYYY-MM-DD") +
        " | 今日"
      );
    }
  }
};
</script>

<style lang="less" scoped>
.el-dialog {
  width: 50% !important;
}
.gray {
  color: #9d9d9d;
}
.board-container {
  position: relative;
  .top-toolbtn {
    position: absolute;
    right: 0;
    top: -5px;
    .el-button {
      margin-left: 30px;
    }
    .editbtn {
      border: 1px solid #0075ff;
      color: #0075ff;
    }
    .addbtn {
      background-color: #0075ff;
      color: #fff;
    }
  }
  .top-box {
    margin-top: 40px;
    .el-col {
      padding-right: 15px;
      .contentbox {
        border-radius: 5px;
        height: 210px;
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 30px;
        color: #fff;

        .num {
          position: relative;
        }
        img {
          width: 100px;
          margin-top: 25px;
        }
        h1,
        h2 {
          padding: 0;
          margin: 0;
          font-weight: 400;
        }
        h1 {
          font-size: 48px;
          margin-top: 10px;
        }
        .percent {
          font-size: 20px;
        }
      }
      .new {
        background-color: #3dd480;
      }
      .buy {
        background-color: #3e97f6;
      }
      .visit {
        background-color: #5c56ec;
      }
      .online {
        background-color: #8648ee;
      }
      hr {
        padding: 0;
        margin: 0;
        position: relative;
        top: -30px;
      }
      .showtime {
        text-align: center;
        position: relative;
        color: #fff;
        top: -30px;
        line-height: 30px;
      }
    }
  }
  .chartsbox {
    .el-col {
      margin-bottom: 15px;
      .chart {
        position: relative;
      }
      :nth-child(2n-1) {
        margin-right: 15px;
      }
    }
    .btn {
      position: absolute;
      right: 0;
      top: 75px;
      z-index: 99;
      img {
        width: 30px;
        height: 28px;
        margin-right: 20px;
      }
    }
  }
  .addbox {
    margin-top: 38px;
    .addborder {
      border: 1px solid #979797;
      border-radius: 8px;
    }
    .checkbox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      p {
        margin: 20px;
        padding: 0;
        font-size: 14px;
      }
      .checkitem {
        width: 100px;
        height: 35px;
        color: red;
        text-align: center;
        font-weight: 600;
        border-bottom: 1px solid #979797;
        margin-right: 47px;
      }
      .active {
        background-color: #e2efff;
        border: 0;
      }
    }
    .picbox {
      height: 413px;
      overflow: hidden;
      img {
        height: 100%;
      }
    }
  }
}
</style>